﻿Option Strict On

Imports System.Management

Public Class ServiceControl

#Region "Enum"
    Public Enum ServiceType As UInteger
        KernalDriver = 1
        FileSystemDriver = 2
        Adapter = 4
        RecognizerDriver = 8
        OwnProcess = 16
        ShareProcess = 32
        InteractiveProcess = 256
    End Enum
    Public Enum ReturnValue
        Success = 0
        NotSupported = 1
        AccessDenied = 2
        DependentServicesRunning = 3
        InvalidServiceControl = 4
        ServiceCannotAcceptControl = 5
        ServiceNotActive = 6
        ServiceRequestTimeout = 7
        UnknownFailure = 8
        PathNotFound = 9
        ServiceAlreadyRunning = 10
        ServiceDatabaseLocked = 11
        ServiceDependencyDeleted = 12
        ServiceDependencyFailure = 13
        ServiceDisabled = 14
        ServiceLogonFailure = 15
        ServiceMarkedForDeletion = 16
        ServiceNoThread = 17
        StatusCircularDependency = 18
        StatusDuplicateName = 19
        StatusInvalidName = 20
        StatusInvalidParameter = 21
        StatusInvalidServiceAccount = 22
        StatusServiceExists = 23
        ServiceAlreadyPaused = 24
        ServiceNotFound = 25
    End Enum
    Public Enum OnError
        UserIsNotNotified = 0
        UserIsNotified = 1
        SystemRestartedLastGoodConfiguraion = 2
        SystemAttemptStartWithGoodConfiguration = 3
    End Enum
    Public Enum StartMode
        Boot = 0
        System = 1
        Automatic = 2
        Manual = 3
        Disabled = 4
    End Enum
    Public Enum ServiceState
        Running
        Stopped
        Paused
        StartPending
        StopPending
        PausePending
        ContinuePending
    End Enum
#End Region

    Public Shared Function StartService() As ReturnValue
        Dim Scope As ManagementScope
        Dim Path As ManagementPath

        Try
            Scope = New ManagementScope("\\.\root\cimv2")
            Path = New ManagementPath("Win32_Service.Name='Hyper-V Backup Scheduler'")
            Scope.Connect()
            Using ManagementObject As New ManagementObject(Scope, Path, Nothing)
                Using outParams As ManagementBaseObject = ManagementObject.InvokeMethod("StartService", Nothing, Nothing)
                    StartService = (DirectCast([Enum].Parse(GetType(ReturnValue), outParams("ReturnValue").ToString), ReturnValue))
                End Using
            End Using
        Catch ex As Exception
            If ex.Message.ToLower().Trim() = "not found" OrElse ex.GetHashCode() = 41149443 Then
                Return ReturnValue.ServiceNotFound
            Else
                Throw ex
            End If
        Finally
            Scope = Nothing
            Path = Nothing
        End Try
    End Function

    Public Shared Function StopService() As ReturnValue
        Dim Scope As ManagementScope
        Dim Path As ManagementPath

        Try
            Scope = New ManagementScope("\\.\root\cimv2")
            Path = New ManagementPath("Win32_Service.Name='Hyper-V Backup Scheduler'")
            Scope.Connect()
            Using ManagementObject As New ManagementObject(Scope, Path, Nothing)
                Using outParams As ManagementBaseObject = ManagementObject.InvokeMethod("StopService", Nothing, Nothing)
                    StopService = (DirectCast([Enum].Parse(GetType(ReturnValue), outParams("ReturnValue").ToString), ReturnValue))
                End Using
            End Using
        Catch ex As Exception
            If ex.Message.ToLower().Trim() = "not found" OrElse ex.GetHashCode() = 41149443 Then
                Return ReturnValue.ServiceNotFound
            Else
                Throw ex
            End If
        Finally
            Scope = Nothing
            Path = Nothing
        End Try
    End Function

    Public Shared Function IsServiceInstalled(ByVal Hostname As String, ConnectionOptions As ConnectionOptions) As Boolean
        Dim ManagementScope As ManagementScope
        Dim ManagementPath As ManagementPath

        Try
            ManagementScope = New ManagementScope("\\" & Hostname & "\root\cimv2", ConnectionOptions)
            ManagementScope.Connect()
            ManagementPath = New ManagementPath("Win32_Service.Name='Hyper-V Backup Scheduler'")

            Using ManagementObject As New ManagementObject(ManagementScope, ManagementPath, Nothing)
                Using outParams As ManagementBaseObject = ManagementObject.InvokeMethod("InterrogateService", Nothing, Nothing)
                    Return True
                End Using
            End Using
        Catch ex As Exception
            If ex.Message.ToLower().Trim() = "not found" OrElse ex.GetHashCode() = 41149443 Then
                Return False
            Else
                Throw ex
            End If
        Finally
            ManagementScope = Nothing
            ManagementPath = Nothing
        End Try

    End Function

    Public Shared Function InstallService(ByVal Hostname As String, ByVal ConnectionOptions As ConnectionOptions) As ReturnValue
        Dim ManagementScope As ManagementScope
        Dim ManagementPath As ManagementPath

        Try
            ManagementScope = New ManagementScope("\\" & Hostname & "\root\cimv2", ConnectionOptions)
            ManagementScope.Connect()
            ManagementPath = New ManagementPath("Win32_Service")

            Using ManagementClass As New ManagementClass(ManagementScope, ManagementPath, Nothing)
                Using inParams As ManagementBaseObject = ManagementClass.GetMethodParameters("create")
                    inParams("Name") = "Hyper-V Backup Scheduler"
                    inParams("DisplayName") = "Hyper-V Backup Scheduler"
                    inParams("PathName") = "C:\Program Files\Poached Productions\Hyper-V Backup\Hyper-V Backup Scheduler.exe"
                    inParams("ServiceType") = ServiceType.OwnProcess
                    inParams("ErrorControl") = 0
                    inParams("StartMode") = StartMode.Automatic
                    inParams("DesktopInteract") = False
                    inParams("StartName") = "LocalSystem"

                    Using outParams As ManagementBaseObject = ManagementClass.InvokeMethod("create", inParams, Nothing)
                        InstallService = DirectCast([Enum].Parse(GetType(ReturnValue), outParams("ReturnValue").ToString()), ReturnValue)
                    End Using
                End Using
            End Using
        Catch ex As Exception
            Throw ex
        Finally
            ManagementScope = Nothing
            ManagementPath = Nothing
        End Try

    End Function
End Class
